using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;

namespace BCBWEB
{
    /// <summary>
    /// This Generic Handler is used for response the get an zoom in image request.
    /// On the client pass a "?image=imageName" to get the image from server side
    /// </summary>
    public class ScaleImage : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string imageName = context.Request.QueryString["image"];

            string WorkingDirectory = @"Product_Images";
            WorkingDirectory = context.Server.MapPath(WorkingDirectory);
            Image imgPhotoVert = Image.FromFile(WorkingDirectory + "\\image\\" + imageName);

            Image imgPhoto = null;

            imgPhoto = ScaleByPercent(imgPhotoVert, 25);

            // return byte array to caller with image type
            context.Response.ContentType = "image/jpeg";
            context.Response.BinaryWrite(GetImageByteStream(imgPhoto));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        static byte[] GetImageByteStream(Image imgPhoto)
        {
            MemoryStream imageStream = new MemoryStream();
            imgPhoto.Save(imageStream, ImageFormat.Jpeg);
            byte[] imageContent = new Byte[imageStream.Length];
            imageStream.Position = 0;
            imageStream.Read(imageContent, 0, (int)imageStream.Length);
            imgPhoto.Dispose();    
            return imageContent;
        }

        static Image ScaleByPercent(Image imgPhoto, int Percent)
        {
            float nPercent = ((float)Percent / 100);

            int sourceWidth = imgPhoto.Width;
            int sourceHeight = imgPhoto.Height;
            int sourceX = 0;
            int sourceY = 0;

            int destX = 0;
            int destY = 0;
            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap bmPhoto = new Bitmap(destWidth, destHeight,
                                     PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                                    imgPhoto.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

            grPhoto.DrawImage(imgPhoto,
                new Rectangle(destX, destY, destWidth, destHeight),
                new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                GraphicsUnit.Pixel);

            grPhoto.Dispose();
            return bmPhoto;
        }
    }
}
